package com.piggy.common.core.exception.base;

import cn.hutool.core.lang.Validator;
import com.piggy.common.core.utils.MessageUtils;
import lombok.Data;

/**
 * 基础异常
 *
 * @author shark
 */
@Data
public class BaseException extends RuntimeException
{
    private static final long serialVersionUID = 1L;

    /**
     * 所属模块
     */
    private String module;

    /**
     * 错误码
     */
    private String code;

    /**
     * 错误码对应的参数
     */
    private Object[] args;

    private Throwable e;

    /**
     * 错误消息
     */
    private String defaultMessage;

    public BaseException(String module, String code, Object[] args, String defaultMessage, Throwable t)
    {
        this.module = module;
        this.code = code;
        this.args = args;
        this.defaultMessage = defaultMessage;
        this.e = t;
    }

    public BaseException(String module, String code, Object[] args, String defaultMessage)
    {
        this(module, code, args, defaultMessage, null);
    }

    @Override
    public String getMessage()
    {
        String message = null;
        if (!Validator.isEmpty(code))
        {
            message = MessageUtils.message(code, args);
        }
        if (message == null)
        {
            message = defaultMessage;
        }
        return message;
    }

    public BaseException(String message, int code, Throwable e)
    {
        this(null, String.valueOf(code), null, message, e);
    }

    public BaseException(String module, String code, Object[] args)
    {
        this(module, code, args, null);
    }

    public BaseException(String module, String defaultMessage)
    {
        this(module, null, null, defaultMessage);
    }

    public BaseException(String code, Object[] args)
    {
        this(null, code, args, null);
    }

    public BaseException(int code, String defaultMessage)
    {
        this(null, String.valueOf(code), null, defaultMessage);
    }

    public BaseException(String defaultMessage)
    {
        this(null, null, null, defaultMessage);
    }

    /**
     * badRequest
     *
     * @param message 错误消息
     * @return 异常
     */
    public static BaseException exception(String message) {
        throw new BaseException(message);
    }

    public BaseException(Throwable cause) {
        super(cause);
    }

    public BaseException(String message, Throwable cause) {
        super(message, cause);
    }

}
